#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define BUFSIZE 50

struct udp_data
{
    short command = 0;   // 0 stand break and exit
    char data[50];
};

int main(){
    int client_sock;
    int len;
    sockaddr_in remote_addr;
    int sin_size;

    char buff[BUFSIZE];
    memset(&remote_addr, 0, sizeof(remote_addr));

    remote_addr.sin_family = AF_INET;
    remote_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    remote_addr.sin_port = htons(55555);

    if(0 > (client_sock = socket(PF_INET, SOCK_DGRAM, 0))){
        perror("failed to create socket .");
        return -1;
    }
    std::cout << "socket created succed !" << std::endl;

    udp_data data;
    data.command = 1;
    strcpy(data.data, "holle-");
    sin_size = sizeof(struct sockaddr);
    udp_data rec;
    while (true)
    {
        strcpy(buff, (char*)&data);
        // std::cout << data.data << std::endl;
        if(len = sendto(client_sock, buff, sizeof(data), 0, (struct sockaddr *)&remote_addr, sizeof(struct sockaddr)) < 0){
            perror("send failed.");
            continue;
        }else if (len = recvfrom(client_sock, buff, sizeof(data), 0, (struct sockaddr *)&remote_addr, (socklen_t *)&sin_size) < 0){
            perror("can not receive feedback.");
            continue;
        }
        memcpy(&rec, &buff, sizeof(rec));
        std::cout << "command " << rec.command << std::endl;
        std::cout << "messege " << rec.data << rec.command << std::endl << std::endl;
        if(0 == rec.command){
            break;
        }
        data.command++;
        data.command %= 100;
    }
    close(client_sock);
}